﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using RN.ERP.DAL.Context;
using Fly.Common.Linq;
using Newtonsoft.Json;
using RN.ERP.Entity.ZBDLRY;
using Fly.Log;
using RN.ERP.BLL.ZBDLRY.Utilities;
using Fly.FlyCommon;
using System.Data;
using RN.ERP.Entity;

namespace RN.ERP.BLL.ZBDLRY
{
    public class KaoHeBLL : BaseKaoHeBll
    {
        #region dbContext
        private ZBDL_Context dbContext
        {
            get
            {
                return (ZBDL_Context)base.baseContext;
            }
        }
        public KaoHeBLL()
        {
            base.baseContext = new ZBDL_Context();
        }
        #endregion

        public override Dictionary<string, double> GetCorpDeDuckList(List<string> corpGuid, string areaCode)
        {
            string corpGuids = string.Format("'{0}',", Guid.Empty);
            foreach (var guidItem in corpGuid)
            {
                corpGuids += string.Format("'{0}',", guidItem);
            }
            corpGuids = corpGuids.TrimEnd(',');

            Dictionary<string, double> returnValue = new ZbdlryDAL.KaoHeDAL().GetCorpDeDuckList(corpGuids, areaCode);

            return returnValue;
        }

        #region 代理考核申请


        public override IList<DTO.CorpSnapInfoForShort> GetCorpSnapList(
            int pageCount,
            int pageSize,
            string conditions,
            int roleId)
        {
            IList<DTO.CorpSnapInfoForShort> snaps = new List<DTO.CorpSnapInfoForShort>();

            #region 查询基础数据

            var dbSnap = dbContext.CorpSnap;
            var dbCompanyInfo = dbContext.Corp_CompanyInfos;
            var dbEvaluation = dbContext.CorpEvaluation;
            IQueryable<DTO.CorpSnapInfoForShort> query = null;
            if (roleId > 0)
            {
                query = from snap in dbSnap
                        join company in dbCompanyInfo on snap.CorpUserGuid equals company.CorpUserGuid
                        join eval in dbEvaluation on snap.KeyGuid equals eval.SnapGuid into jEval
                        from evals in jEval.DefaultIfEmpty()
                        where snap.IsDel == false && evals.CorpUserGuid == evals.IsrtUserGuid && evals.PostState == 1
                        select new DTO.CorpSnapInfoForShort()
                        {
                            AppId = snap.AppId,
                            AreaCode = snap.AreaCode,
                            CorpUserGuid = snap.CorpUserGuid,
                            Id = snap.Id,
                            IsDel = snap.IsDel,
                            IsrtDate = snap.IsrtDate,
                            KeyGuid = snap.KeyGuid,
                            CorpName = company.CorpName,
                            EvalGuid = evals.KeyGuid,
                            PostState = evals.PostState,
                            ShenheStr = snap.ShenheStr
                        };
            }
            else
            {
                query = from snap in dbSnap
                        join company in dbCompanyInfo on snap.CorpUserGuid equals company.CorpUserGuid
                        join eval in dbEvaluation on snap.KeyGuid equals eval.SnapGuid into jEval
                        from evals in jEval.DefaultIfEmpty()
                        where snap.IsDel == false && ((evals.KeyGuid == null) || (evals.KeyGuid != null && evals.CorpUserGuid == evals.IsrtUserGuid))
                        select new DTO.CorpSnapInfoForShort()
                        {
                            AppId = snap.AppId,
                            AreaCode = snap.AreaCode,
                            CorpUserGuid = snap.CorpUserGuid,
                            Id = snap.Id,
                            IsDel = snap.IsDel,
                            IsrtDate = snap.IsrtDate,
                            KeyGuid = snap.KeyGuid,
                            CorpName = company.CorpName,
                            EvalGuid = evals.KeyGuid,
                            PostState = evals.PostState,
                            ShenheStr = snap.ShenheStr
                        };
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<DTO.QueryCorpSnapInfoCondition>(conditions);
                query = query.BuildCondition<DTO.CorpSnapInfoForShort>(condition);
            }
            if (pageSize > 0)
            {
                snaps = query.OrderByDescending(s => s.IsrtDate)
                    .Skip((pageCount - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();
            }
            else
            {
                snaps = query.OrderByDescending(s => s.IsrtDate).ToList();
            }

            #endregion

            #region 后期数据处理

            IList<Tb_Corp_Evaluation_Zbdl> evaluations = new List<Tb_Corp_Evaluation_Zbdl>();

            if (roleId > 0)
            {
                List<Guid> snapGuids = snaps.Select(s => s.KeyGuid).ToList();
                var query1 = from eval in dbEvaluation
                             where eval.IsDel == false && snapGuids.Contains(eval.SnapGuid) && eval.IsrtUserRole == roleId
                             select eval;
                evaluations = query1.ToList();
            }

            foreach (DTO.CorpSnapInfoForShort snap in snaps)
            {
                if (roleId > 0)
                {
                    var evaluation = evaluations.Where(e => e.SnapGuid == snap.KeyGuid).ToList();
                    if (evaluation.Count > 0)
                    {
                        switch (evaluation[0].PostState)
                        {
                            case 0:
                                snap.StatusTitle = "已添加自评表";
                                snap.Status = 1;
                                break;
                            case 1:
                                snap.StatusTitle = "已上报自评表";
                                snap.Status = 2;
                                break;
                        }
                    }
                    else
                    {
                        snap.StatusTitle = "未添加自评表";
                        snap.Status = 0;
                    }
                }
                else
                {
                    if (snap.EvalGuid == null)
                    {
                        snap.StatusTitle = "未添加自评表";
                        snap.Status = 0;
                    }
                    else
                    {
                        switch (snap.PostState)
                        {
                            case 0:
                                snap.StatusTitle = "已添加自评表";
                                snap.Status = 1;
                                break;
                            case 1:
                                snap.StatusTitle = "已上报自评表";
                                snap.Status = 2;
                                break;
                        }
                    }
                }
            }

            #endregion

            return snaps;
        }

        /// <summary>
        /// 返回申请信息
        /// </summary>
        /// <param name="keyGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="appId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetCorpSnap(string keyGuid, string snapType, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            Guid snapGuid = Guid.Empty;
            if (!Guid.TryParse(keyGuid, out snapGuid))
            {
                result.Result = false;
                result.Message = "申请信息不正确！";
                return result;
            }
            var corpSnap = dbContext.CorpSnap.Where(c => c.KeyGuid == snapGuid && c.IsDel != true).FirstOrDefault();
            if (corpSnap == null)
            {
                result.Result = false;
                result.Message = "未查询到有效的申请信息！";
                return result;
            }
            switch (snapType)
            {
                case "CorpSnap":////企业基本信息
                    result.ReturnValue = corpSnap.CorpSnap;
                    break;
                case "ManagerSnap":////执业人员
                    result.ReturnValue = corpSnap.ManagerSnap;
                    break;
                case "PsnPostSnap":////中级以上职称人员
                    result.ReturnValue = corpSnap.PsnPostSnap;
                    break;
                case "CorpSystemSnap":////规章制度
                    result.ReturnValue = corpSnap.CorpSystemSnap;
                    break;
                case "All":////返回全部
                    result.ReturnValue = corpSnap;
                    break;

            }
            return result;
        }

        /// <summary>
        /// 添加信用申请
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="appId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpSnapAdd(string corpUserGuid, string appId, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                ////判断申请是否存在              
                result = CheckCorpSnapYearIsExist(corpUserGuid, areaCode);
                if (!result.Result)
                {
                    return result;
                }

                ////取得实体信息
                Tb_Corp_CompanyInfo_Zbdl companyInfo = (Tb_Corp_CompanyInfo_Zbdl)result.ReturnValue;
                DTO.OperationResult result1 = GetCorpSnapInfo(Guid.NewGuid(), companyInfo.CorpUserGuid, appId, areaCode);
                if (!result1.Result)
                {
                    return result1;
                }
                Tb_Corp_Snap_Zbdl corpSnap = (Tb_Corp_Snap_Zbdl)result1.ReturnValue;
                corpSnap = dbContext.CorpSnap.Add(corpSnap);
                dbContext.SaveChanges();
                ////添加日志
                SetUserLog("添加信用申请信息", corpSnap.KeyGuid.ToString(), corpUserGuid, areaCode, "1");
                result.ReturnValue = true;
                result.ReturnValue = corpSnap.KeyGuid;
                result.Message = "信用申请保存成功！";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "申请保存失败" + ex.InnerException;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 修改信用申请
        /// </summary>
        /// <param name="keyGuid"></param>
        /// <param name="appId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpSnapEdit(string keyGuid, string appId, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                ////判断申请状态
                result = CheckCorpSnapStatus(keyGuid, 1);
                if (!result.Result)
                {
                    return result;
                }
                ////取得实体信息
                Tb_Corp_Snap_Zbdl corpSnap = (Tb_Corp_Snap_Zbdl)result.ReturnValue;
                DTO.OperationResult result1 = GetCorpSnapInfo(corpSnap.KeyGuid, corpSnap.CorpUserGuid, appId, areaCode);
                if (!result1.Result)
                {
                    return result1;
                }
                var corpSnap1 = (Tb_Corp_Snap_Zbdl)result1.ReturnValue;
                EntityHelper.ConvertEntity2Entity<Tb_Corp_Snap_Zbdl>(corpSnap1, corpSnap);
                dbContext.SaveChanges();
                ////添加日志
                SetUserLog("修改信用申请信息", corpSnap.KeyGuid.ToString(), corpSnap.CorpUserGuid.ToString(), areaCode, "2");
                result.ReturnValue = true;
                result.ReturnValue = corpSnap.KeyGuid;
                result.Message = "信用申请保存成功！";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "申请保存失败" + ex.InnerException;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 删除信用申请
        /// </summary>
        /// <param name="keyGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpSnapDel(string keyGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                ////判断申请状态
                result = CheckCorpSnapStatus(keyGuid, 1);
                if (!result.Result)
                {
                    return result;
                }
                Tb_Corp_Snap_Zbdl corpSnap = (Tb_Corp_Snap_Zbdl)result.ReturnValue;
                corpSnap.IsDel = true;
                dbContext.SaveChanges();
                ////添加日志
                SetUserLog("删除信用申请信息", corpSnap.KeyGuid.ToString(), corpSnap.CorpUserGuid.ToString(), areaCode, "3");
                result.ReturnValue = true;
                result.Message = "信用申请删除成功！";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "申请删除失败" + ex.InnerException;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 申请上报
        /// </summary>
        /// <param name="keyGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpSnapPost(string keyGuid, string corpUserGuid, string isrtUserGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid isrtGuid = Guid.Empty;
            if (!Guid.TryParse(isrtUserGuid, out isrtGuid))
            {
                result.Result = false;
                result.Message = "信息不正确！";
                return result;
            }
            try
            {
                ////判断申请状态
                result = CheckCorpSnapIsExist(keyGuid, corpUserGuid, 1);
                if (!result.Result)
                {
                    return result;
                }
                Tb_Corp_Snap_Zbdl corpSnap = (Tb_Corp_Snap_Zbdl)result.ReturnValue;
                var corpEval = dbContext.CorpEvaluation.Where(c => c.CorpUserGuid == corpSnap.CorpUserGuid && c.SnapGuid == corpSnap.KeyGuid && c.IsrtUserGuid == isrtGuid).FirstOrDefault();
                if (corpEval == null)
                {
                    result.Result = false;
                    result.Message = "评价信息不存在，无法上报！";
                    return result;
                }
                ////修改申请状态
                if (corpSnap.Status == 0)
                {
                    corpSnap = dbContext.CorpSnap.Where(c => c.KeyGuid == corpSnap.KeyGuid).FirstOrDefault();
                    corpSnap.Status = 1;
                    dbContext.SaveChanges();
                }
                ////修改评价状态
                if (corpEval.PostState == 0)
                {
                    corpEval.PostState = 1;
                    dbContext.SaveChanges();
                }
                else
                {
                    result.Result = false;
                    result.Message = "评价信息已上报！";
                    return result;
                }
                ////添加日志
                SetUserLog("信用申请评价上报", corpSnap.KeyGuid.ToString(), corpSnap.CorpUserGuid.ToString(), areaCode, "4");
                result.ReturnValue = true;
                result.Message = "信用申请上报成功！";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "申请上报失败" + ex.InnerException;
                result.Result = false;
            }
            return result;
        }

        public override DTO.OperationResult CorpCancel(
            string snapGuid,
            string isrtUserGuid,
            string areaCode,
            bool isAll,
            string content,
            string isrtUserRole)
        {
            Guid gSnapGuid = Guid.Empty;
            Guid gIsrtUserGuid = Guid.Empty;
            Guid.TryParse(snapGuid, out gSnapGuid);
            Guid.TryParse(isrtUserGuid, out gIsrtUserGuid);
            if (gSnapGuid != Guid.Empty && gIsrtUserGuid != Guid.Empty)
            {
                var snap = dbContext.CorpSnap.SingleOrDefault(cs => cs.KeyGuid == gSnapGuid && cs.IsDel == false);
                if (snap != null)
                {
                    snap.Status = 0;
                    ////吴振华要求，加入的退回意见功能，2014-06-24
                    Dictionary<string, string> shenhe = new Dictionary<string, string>();
                    if (string.IsNullOrEmpty(snap.ShenheStr))
                    {
                        shenhe.Add(isrtUserRole.ToLower(), content);
                    }
                    else
                    {
                        shenhe = JsonConvert.DeserializeObject<Dictionary<string, string>>(snap.ShenheStr);
                        if (shenhe.ContainsKey(isrtUserRole.ToLower()))
                        {
                            shenhe[isrtUserRole.ToLower()] = content;
                        }
                        else
                        {
                            shenhe.Add(isrtUserRole.ToLower(), content);
                        }
                    }
                    snap.ShenheStr = JsonConvert.SerializeObject(shenhe);
                    ////end
                    dbContext.SaveChanges();
                    if (isAll)
                    {
                        var evals = dbContext.CorpEvaluation.Where(ce => ce.SnapGuid == gSnapGuid && ce.IsDel == false).ToList();
                        foreach (Tb_Corp_Evaluation_Zbdl eval in evals)
                        {
                            eval.PostState = 0;
                        }
                        dbContext.SaveChanges();
                    }
                    else
                    {
                        var evals = dbContext.CorpEvaluation.Where(ce => ce.SnapGuid == gSnapGuid && (ce.IsrtUserGuid == snap.CorpUserGuid || ce.IsrtUserGuid == gIsrtUserGuid));
                        foreach (Tb_Corp_Evaluation_Zbdl eval in evals)
                        {
                            eval.PostState = 0;
                        }
                        dbContext.SaveChanges();
                    }

                    return new DTO.OperationResult()
                    {
                        Result = true,
                        Message = "退回成功"
                    };
                }
                else
                {
                    return new DTO.OperationResult()
                    {
                        Result = false,
                        Message = "未找到"
                    };
                }
            }
            else
            {
                return new DTO.OperationResult()
                {
                    Result = false,
                    Message = "参数不正确！"
                };
            }
        }

        /// <summary>
        /// 申报评价。
        /// </summary>
        /// <param name="keyGuid"></param>
        /// <returns></returns>
        public DTO.OperationResult CorpEvalPost(string keyGuid)
        {
            Tb_Corp_Snap_Zbdl snap = new Tb_Corp_Snap_Zbdl(); ;
            Tb_Corp_Evaluation_Zbdl eval = new Tb_Corp_Evaluation_Zbdl();
            ////1.数据验证。
            DTO.OperationResult result = ValidateEvalPost(
                keyGuid,
                out snap,
                out eval);
            if (!result.Result)
            {
                return result;
            }

            int id = snap.Id;

            return result;
        }

        private DTO.OperationResult ValidateEvalPost(
            string keyGuid,
            out Tb_Corp_Snap_Zbdl snap,
            out Tb_Corp_Evaluation_Zbdl eval)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            snap = new Tb_Corp_Snap_Zbdl();
            eval = new Tb_Corp_Evaluation_Zbdl();
            Guid gKeyGuid = Guid.Empty;
            if (!Guid.TryParse(keyGuid, out gKeyGuid))
            {
                result.Result = false;
                result.Message = "输入GUID不正确！";
                return result;
            }
            var evaluations = dbContext.CorpEvaluation.Where(e => e.KeyGuid == gKeyGuid && e.IsDel == false).ToList();
            if (evaluations.Count == 0)
            {
                result.Result = false;
                result.Message = "此评价记录不存在！";
                return result;
            }
            eval = evaluations[0];
            if (eval.PostState != 0)
            {
                result.Result = false;
                result.Message = "此评价记录已经申报！";
                return result;
            }
            Guid snapGuid = eval.SnapGuid;
            var snaps = dbContext.CorpSnap.Where(s => s.KeyGuid == snapGuid && s.IsDel == false).ToList();
            if (snaps.Count == 0)
            {
                result.Result = false;
                result.Message = "此评价记录的企业基本情况申请表不存在！";
                return result;
            }
            if (snaps.Count > 1)
            {
                result.Result = false;
                result.Message = "此评价记录的企业基本情况申请表异常！";
                return result;
            }
            snap = snaps[0];
            return result;
        }

        /// <summary>
        /// 验证申请状态
        /// </summary>
        /// <param name="corpSnapGuid"></param>
        /// <returns></returns>
        public override DTO.OperationResult CheckCorpSnapStatus(string corpSnapGuid, int flag)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid keyGuid = Guid.Empty;
            if (!Guid.TryParse(corpSnapGuid, out keyGuid))
            {
                result.Result = false;
                result.Message = "申请信息不正确！";
                return result;
            }
            var corpSnap = dbContext.CorpSnap.Where(c => c.KeyGuid == keyGuid && c.IsDel != true).FirstOrDefault();
            if (corpSnap == null)
            {
                result.Result = false;
                result.Message = "没有查询到申请信息！";
                return result;
            }
            if (corpSnap.Status > 0)
            {
                result.Result = false;
                result.Message = "申请信息已上报，不能再修改！";
                return result;
            }
            result.Result = true;
            if (flag > 0)
            {
                result.ReturnValue = corpSnap;
            }
            return result;
        }

        /// <summary>
        /// 添加修改企业规章制度
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="regulatory"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CompanyRegulatoryEdit(string corpUserGuid, string regulatory, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            if (string.IsNullOrEmpty(regulatory))
            {
                result.Result = false;
                result.Message = "规章制度不能为空！";
                return result;
            }
            try
            {
                ////判断企业是否存在
                result = CheckCompanyIsExist(corpUserGuid);
                if (!result.Result)
                {
                    return result;
                }
                ////取得企业信息
                Tb_Corp_CompanyInfo_Zbdl companyInfo = (Tb_Corp_CompanyInfo_Zbdl)result.ReturnValue;
                var corpAttachInfo = dbContext.CorpAttachInfo.Where(o => o.CorpUserGuid == companyInfo.CorpUserGuid && o.IsDel != true).FirstOrDefault();
                if (corpAttachInfo == null)
                {
                    ////添加
                    Tb_Corp_AttachInfo_Zbdl newCorpAttachInfo = new Tb_Corp_AttachInfo_Zbdl();
                    newCorpAttachInfo.CorpUserGuid = companyInfo.CorpUserGuid;
                    newCorpAttachInfo.Content3 = regulatory;
                    newCorpAttachInfo.IsrtDate = DateTime.Now;
                    newCorpAttachInfo.IsDel = false;
                    dbContext.CorpAttachInfo.Add(newCorpAttachInfo);
                    dbContext.SaveChanges();

                }
                else
                {
                    ////修改
                    corpAttachInfo.Content3 = regulatory;
                    corpAttachInfo.IsrtDate = DateTime.Now;
                    dbContext.SaveChanges();
                }
                ////添加日志
                SetUserLog("编辑管理规章制度！", corpAttachInfo.Id.ToString(), corpUserGuid, areaCode, "1");
                result.ReturnValue = true;
                result.ReturnValue = corpAttachInfo.Id;
                result.Message = "企业规章制度保存成功！";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "企业规章制度保存失败" + ex.InnerException;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 返回规章制度信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetCompanyRegulatory(string corpUserGuid, string areaCode)
        {
            Guid corpGuid = Guid.Empty;
            string remark = string.Empty;
            if (Guid.TryParse(corpUserGuid, out corpGuid))
            {
                var result = dbContext.CorpAttachInfo.Where(o => o.CorpUserGuid == corpGuid && o.IsDel != true).FirstOrDefault();
                if (result != null)
                {
                    remark = result.Content3;
                }
            }
            return remark;
        }

        /// <summary>
        /// 修改人员社保号
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="insuranceNum"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult PersonEmpInsuranceNumEdit(string empGuid, string corpUserGuid, string insuranceNum, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            try
            {
                ////判断人员是否存在
                result = new PersonBLL().CheckEmpIsExist(empGuid);
                if (!result.Result)
                {
                    return result;
                }
                ////人员
                tb_Emp_Manager_Zbdl currentManager = (tb_Emp_Manager_Zbdl)result.ReturnValue;
                var emp = dbContext.Emp_Manager.Where(m => m.EmpGuid == currentManager.EmpGuid).FirstOrDefault();
                emp.InsuranceNum = insuranceNum;
                dbContext.SaveChanges();
                ////添加日志
                SetUserLog("修改人员社保号信息", currentManager.EmpGuid.ToString(), corpUserGuid.ToString(), areaCode, "2");
                result.ReturnValue = true;
                result.Message = "人员社保号保存成功！";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "人员社保号保存失败" + ex.InnerException;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 修改企业开户行
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="regulatory"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CompanyBankEdit(string corpUserGuid, string bankName, string bankAccNo, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            if (string.IsNullOrEmpty(bankName) || string.IsNullOrEmpty(bankAccNo))
            {
                result.Result = false;
                result.Message = "开户行信息不完整！";
                return result;
            }
            try
            {
                ////判断企业是否存在
                result = CheckCompanyIsExist(corpUserGuid);
                if (!result.Result)
                {
                    return result;
                }
                ////取得企业信息
                Tb_Corp_CompanyInfo_Zbdl companyInfo = (Tb_Corp_CompanyInfo_Zbdl)result.ReturnValue;
                companyInfo.BankName = bankName;
                companyInfo.BankAccNo = bankAccNo;
                dbContext.SaveChanges();

                ////添加日志
                SetUserLog("编辑企业开户行信息！", corpUserGuid, corpUserGuid, areaCode, "1");
                result.ReturnValue = true;
                result.Message = "企业开户行信息保存成功！";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "企业开户行信息保存失败" + ex.InnerException;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 判断企业本年度的申请信息是否存在
        /// </summary>
        /// <param name="corpSnapGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public override DTO.OperationResult CheckCorpSnapYearIsExist(string corpUserGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            ////判断企业是否存在
            result = CheckCompanyIsExist(corpUserGuid);
            if (!result.Result)
            {
                return result;
            }
            ////取得实体信息
            Tb_Corp_CompanyInfo_Zbdl companyInfo = (Tb_Corp_CompanyInfo_Zbdl)result.ReturnValue;
            ////查询最新的申请信息
            var corpSnap = dbContext.CorpSnap.Where(c => c.CorpUserGuid == companyInfo.CorpUserGuid && c.IsDel != true).OrderByDescending(c => c.IsrtDate).FirstOrDefault();
            if (corpSnap != null)
            {
                if (corpSnap.IsrtDate.HasValue)
                {
                    if (corpSnap.IsrtDate.GetValueOrDefault().Year == DateTime.Now.Year)
                    {
                        result.Result = false;
                        result.Message = "每年只能添加一条申请信息，本年度信用申请已经存在，不能再添加！";
                        return result;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 判断企业的申请信息是否存在
        /// </summary>
        /// <param name="corpSnapGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckCorpSnapIsExist(string corpSnapGuid, string corpUserGuid, int flag)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            ////判断企业是否存在
            result = CheckCompanyIsExist(corpUserGuid);
            if (!result.Result)
            {
                return result;
            }
            ////取得实体信息
            Tb_Corp_CompanyInfo_Zbdl companyInfo = (Tb_Corp_CompanyInfo_Zbdl)result.ReturnValue;
            Guid keyGuid = Guid.Empty;
            if (!Guid.TryParse(corpSnapGuid, out keyGuid))
            {
                result.Result = false;
                result.Message = "申请信息不正确！";
                return result;
            }
            var corpSnap = dbContext.CorpSnap.Where(c => c.KeyGuid == keyGuid && c.CorpUserGuid == companyInfo.CorpUserGuid && c.IsDel != true).FirstOrDefault();
            if (corpSnap == null)
            {
                result.Result = false;
                result.Message = "没有查询到申请信息！";
                return result;
            }
            result.ReturnValue = new Tb_Corp_Snap_Zbdl
            {
                CorpUserGuid = corpSnap.CorpUserGuid,
                KeyGuid = corpSnap.KeyGuid,
                Status = corpSnap.Status
            };
            return result;
        }

        /// <summary>
        /// 返回申请实体
        /// </summary>
        /// <param name="keyGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="appId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult GetCorpSnapInfo(Guid keyGuid, Guid corpUserGuid, string appId, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            Tb_Corp_Snap_Zbdl corpSnap = new Tb_Corp_Snap_Zbdl();
            corpSnap.CorpUserGuid = corpUserGuid;
            corpSnap.KeyGuid = keyGuid;

            ////取得企业信息
            DTO.OperationResult result3 = GetCompanyInfo(corpUserGuid, areaCode);
            if (!result3.Result)
            {
                return result3;
            }
            corpSnap.CorpSnap = result3.ReturnValue.ToString();
            ////取得中级以上职称人员
            DTO.OperationResult result1 = GetPersonPost(corpUserGuid, areaCode);
            if (!result1.Result)
            {
                return result1;
            }
            corpSnap.PsnPostSnap = result1.ReturnValue.ToString();
            ////取得执业人员
            DTO.OperationResult result2 = GetPersonCert(corpUserGuid, areaCode);
            if (!result2.Result)
            {
                return result2;
            }
            corpSnap.ManagerSnap = result2.ReturnValue.ToString();
            ////取得企业规章制度
            string remart = GetCompanyRegulatory(corpUserGuid.ToString(), areaCode);
            corpSnap.CorpSystemSnap = remart;

            corpSnap.IsrtDate = DateTime.Now;
            corpSnap.IsDel = false;
            corpSnap.Status = 0;
            corpSnap.AppId = appId;
            corpSnap.AreaCode = areaCode;
            result.ReturnValue = corpSnap;
            return result;
        }

        /// <summary>
        /// 判断企业是否存在
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckCompanyIsExist(string corpUserGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid corpGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out corpGuid))
            {
                result.Result = false;
                result.Message = "企业信息不正确！";
                return result;
            }
            var companyInfo = dbContext.Corp_CompanyInfos.Where(c => c.CorpUserGuid == corpGuid && c.IsDel != true).FirstOrDefault();
            if (companyInfo != null)
            {
                result.Result = true;
                result.ReturnValue = companyInfo;
            }
            else
            {
                result.Result = false;
                result.Message = "没有查询到企业信息！";
            }
            return result;

        }

        /// <summary>
        /// 取得企业基本信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult GetCompanyInfo(Guid corpUserGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            BaseEnterpriseBLL enterpriseBll = (BaseEnterpriseBLL)BllFactory.CreateBll(BllType.Enterprise, areaCode);
            result.ReturnValue = JsonConvert.SerializeObject(enterpriseBll.GetCompanyBusinessInfoKH(corpUserGuid.ToString(), "", areaCode));
            return result;
        }

        /// <summary>
        /// 取得中级以上职称专职人员
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult GetPersonPost(Guid corpUserGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            PersonBLL bll = new PersonBLL();
            string queryStr = GetQueryConditions(corpUserGuid, "03", string.Empty);
            int count = bll.GetEmpManagerListCount(queryStr, areaCode);
            if (count > 0)
            {
                result.ReturnValue = JsonConvert.SerializeObject(bll.GetEmpManagersList(0, 0, queryStr, areaCode));
            }
            else
            {
                result.Result = false;
                result.Message = "企业没有中级以上职称专职人员，不能上报！";
            }
            return result;
        }

        /// <summary>
        /// 取得工程建设类执业注册人员
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult GetPersonCert(Guid corpUserGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            PersonBLL bll = new PersonBLL();
            string queryStr = GetQueryConditions(corpUserGuid, string.Empty, "71,72,0,60,61");
            int count = bll.GetEmpManagerListCount(queryStr, areaCode);
            if (count > 0)
            {
                result.ReturnValue = JsonConvert.SerializeObject(bll.GetEmpManagersList(0, 0, queryStr, areaCode));
            }
            else
            {
                result.Result = false;
                result.Message = "企业没有工程建设类执业注册人员，不能上报！";
            }
            return result;
        }

        /// <summary>
        /// 取得人员查询参数列表
        /// </summary>
        /// <returns></returns>
        private string GetQueryConditions(Guid corpUserGuid, string postpsZG, string itemType)
        {
            ////设置查询参数
            DTO.QueryPersonInfoCondition queryCondition = new DTO.QueryPersonInfoCondition();
            ////审核状态
            // queryCondition.FlowCode = new ParameterValue<string> { V = "1,", O = OptEnum.StartWith };
            ////职称
            if (!string.IsNullOrEmpty(postpsZG))
            {
                queryCondition.Post_psZG = new ParameterValue<string> { V = postpsZG, O = OptEnum.LessThanOrEqual };
            }
            ////证书类型包含多种类型的人员
            if (!string.IsNullOrEmpty(itemType))
            {
                int code = 0;
                var list = new List<ParameterValue<int>>();
                string[] arrt = itemType.Split(',');
                foreach (var a in arrt)
                {
                    if (int.TryParse(a.Trim(), out code))
                    {
                        var area = new ParameterValue<int>() { O = OptEnum.Equal, V = code };
                        list.Add(area);
                    }
                }
                queryCondition.TypeFlags = new ParameterValues<int>()
                {
                    Logic = LogicEnum.Or,
                    Values = list
                };
            }
            ////企业guid
            queryCondition.CorpGuid = new ParameterValue<Guid> { V = corpUserGuid, O = OptEnum.Equal };
            List<DTO.QueryPersonInfoCondition> query = new List<DTO.QueryPersonInfoCondition>();
            query.Add(queryCondition);
            return JsonConvert.SerializeObject(query);
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ObjectId"></param>
        /// <param name="IsrtUser"></param>
        /// <param name="IsrtUserName"></param>
        /// <param name="areaCode"></param>
        /// <param name="FunctionType"></param>
        /// <param name="codeType"></param>
        /// <returns></returns>
        private bool SetUserLog(string message, string objectId, string corpUserGuid, string areaCode, string FunctionType)
        {
            DTO.OperationResult result = CheckCompanyIsExist(corpUserGuid);
            if (!result.Result)
            {
                return result.Result;
            }
            Tb_Corp_CompanyInfo_Zbdl companyInfo = (Tb_Corp_CompanyInfo_Zbdl)result.ReturnValue;
            LogAndFlowHelper loghelper = new LogAndFlowHelper();
            loghelper.InsertDetailUserLog(message, objectId, companyInfo.classID.ToString(), FunctionType, new User_Log()
            {
                IsrtDate = DateTime.Now,
                IsrtUserArea = areaCode,
                IsrtUser = corpUserGuid,
                IsrtUserName = companyInfo.CorpName,
            });
            return true;
        }

        #endregion

        #region 代理考核评分

        /// <summary>
        /// 添加修改评分参数指标数据
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="regulatory"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult CorpEvaluationParamsEdit(string corpUserGuid, string evaluationParams, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            if (string.IsNullOrEmpty(evaluationParams))
            {
                result.Result = false;
                result.Message = "评分参数指标数据不能为空！";
                return result;
            }
            try
            {
                ////判断企业是否存在
                result = CheckCompanyIsExist(corpUserGuid);
                if (!result.Result)
                {
                    return result;
                }
                ////取得企业信息
                Tb_Corp_CompanyInfo_Zbdl companyInfo = (Tb_Corp_CompanyInfo_Zbdl)result.ReturnValue;
                var corpAttachInfo = dbContext.CorpAttachInfo.Where(o => o.CorpUserGuid == companyInfo.CorpUserGuid && o.IsDel != true).FirstOrDefault();
                if (corpAttachInfo == null)
                {
                    ////添加
                    Tb_Corp_AttachInfo_Zbdl newCorpAttachInfo = new Tb_Corp_AttachInfo_Zbdl();
                    newCorpAttachInfo.CorpUserGuid = companyInfo.CorpUserGuid;
                    newCorpAttachInfo.Content4 = evaluationParams;
                    newCorpAttachInfo.IsrtDate = DateTime.Now;
                    newCorpAttachInfo.IsDel = false;
                    dbContext.CorpAttachInfo.Add(newCorpAttachInfo);
                    dbContext.SaveChanges();

                }
                else
                {
                    ////修改
                    corpAttachInfo.Content4 = evaluationParams;
                    corpAttachInfo.IsrtDate = DateTime.Now;
                    dbContext.SaveChanges();
                }
                ////添加日志
                SetUserLog("编辑评分参数指标！", corpAttachInfo.Id.ToString(), corpUserGuid, areaCode, "1");
                result.ReturnValue = true;
                result.ReturnValue = corpAttachInfo.Id;
                result.Message = "评分参数指标保存成功！";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "评分参数指标保存失败" + ex.InnerException;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 返回评分参数指标
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetCorpAttachInfo(string corpUserGuid, string content, string areaCode)
        {
            Guid corpGuid = Guid.Empty;
            string remark = string.Empty;
            if (Guid.TryParse(corpUserGuid, out corpGuid))
            {
                var result = dbContext.CorpAttachInfo.Where(o => o.CorpUserGuid == corpGuid && o.IsDel != true).FirstOrDefault();
                if (result != null)
                {
                    switch (content.ToLower())
                    {
                        case "content4":
                            remark = result.Content4;
                            break;
                        default:
                            remark = result.Content4;
                            break;
                    }
                }
            }
            return remark;
        }

        /// <summary>
        /// 取得评分项列表
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="classId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override List<DTO.Corp_EvaluationScore> GetCorpEvaluationItems(int evaluationId, string appId, int classId, string areaCode)
        {
            var list = dbContext.CorpEvaluationItem.Where(c => c.IsDel != true && c.ClassId == classId && c.ParentID == 0).ToList();
            List<DTO.Corp_EvaluationScore> list_D = new List<DTO.Corp_EvaluationScore>();
            ////实体转换
            foreach (Tb_Corp_EvaluationItem_Zbdl item in list)
            {
                DTO.Corp_EvaluationScore work_D = new DTO.Corp_EvaluationScore();
                work_D.Id = item.Id;
                work_D.MaxScore = item.MaxScore;
                work_D.ParentID = item.ParentID;
                work_D.SortIndex = item.SortIndex;
                work_D.Title = item.Title;
                work_D.Type = item.Type;
                var items = GetCorpEvaluationScore(evaluationId, 0, item.Id, appId, classId, areaCode);
                work_D.EvaluationItems = items;
                ////计算自评分
                decimal score = items.Select(i => i.Score).Sum().HasValue ? (decimal)items.Select(i => i.Score).Sum() : 0;
                work_D.Score = GetScore(item.MaxScore, score, item.Type);
                list_D.Add(work_D);
            }
            return list_D;
        }

        /// <summary>
        /// 计算自评分
        /// </summary>
        /// <param name="maxScore"></param>
        /// <param name="score"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private decimal GetScore(decimal maxScore, decimal score, string type)
        {
            if (type == "0")
            {
                return maxScore < score ? maxScore : score;
            }
            else
            {
                return maxScore < score ? 0 : maxScore - score;
            }
        }

        /// <summary>
        /// 计算总分
        /// </summary>
        /// <param name="evaluationId"></param>
        /// <returns></returns>
        private decimal GetScoreSum(int evaluationId, string appId, int classId, string areaCode)
        {
            decimal scoreSum = 0;
            var list = dbContext.CorpEvaluationItem.Where(c => c.IsDel != true && c.ClassId == classId && c.ParentID == 0).ToList();
            foreach (Tb_Corp_EvaluationItem_Zbdl item in list)
            {
                var items = GetCorpEvaluationScore(evaluationId, 0, item.Id, appId, classId, areaCode);
                ////计算自评分
                decimal score = items.Select(i => i.Score).Sum().HasValue ? (decimal)items.Select(i => i.Score).Sum() : 0;
                scoreSum += GetScore(item.MaxScore, score, item.Type);
            }
            return scoreSum;
            //////按评分项分类计算自评得分
            //var query = from evalSub in dbContext.CorpEvaluationSub
            //            join evalItem in dbContext.CorpEvaluationItem on evalSub.ItemId equals evalItem.Id
            //            where evalItem.IsDel != true && evalSub.IsDel != true && evalSub.TreeId == evaluationId
            //            group evalSub by evalItem.ParentID into g
            //            select new
            //            {
            //                Key=g.Key,
            //                Score = g.Sum(p => p.Score)
            //            };
            //var scores=query.ToList();
            //////计算自评总得分
            //decimal score = 0;
            //decimal scoreSum = 0;
            //foreach (var item in scores)
            //{
            //    var scoreMaxs = dbContext.CorpEvaluationItem.Where(c => c.IsDel != true && c.Id == item.Key).FirstOrDefault();
            //    if (scoreMaxs != null)
            //    {
            //        score = item.Score ?? 0;
            //        scoreSum += GetScore(scoreMaxs.MaxScore, score, scoreMaxs.Type);
            //    }
            //    else
            //    {
            //        scoreSum += 0;
            //    }
            //}
            //return scoreSum;            
        }

        /// <summary>
        /// 取得当前用户的信用评价主表ID
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="snapGuid"></param>
        /// <param name="isrtUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetCorpEvaluationScoreID(string corpUserGuid, string snapGuid, string isrtUserGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            Guid isrtGuid = Guid.Empty;
            if (!Guid.TryParse(isrtUserGuid, out isrtGuid))
            {
                result.Result = false;
                result.Message = "评分人信息不正确！";
                return result;
            }
            ////判断企业申请是否存在
            result = CheckCorpSnapIsExist(snapGuid, corpUserGuid, 0);
            if (!result.Result)
            {
                return result;
            }
            ////取得实体信息
            var corpSnap = (Tb_Corp_Snap_Zbdl)result.ReturnValue;
            ////评价表存在返回评价表ID
            var corpEval = dbContext.CorpEvaluation.Where(c => c.CorpUserGuid == corpSnap.CorpUserGuid && c.SnapGuid == corpSnap.KeyGuid && c.IsrtUserGuid == isrtGuid && c.IsDel != true).FirstOrDefault();
            if (corpEval != null)
            {
                result.ReturnValue = corpEval.Id;
            }
            else
            {
                ////创建当前用户的评价信息并返回ID
                DTO.OperationResult result1 = CorpEvaluationScoreAdd(corpSnap.CorpUserGuid, corpSnap.KeyGuid, isrtGuid, areaCode);
                if (!result1.Result)
                {
                    return result1;
                }
                result.ReturnValue = result1.ReturnValue;
            }
            return result;
        }

        /// <summary>
        /// 返回评分项及分值列表
        /// </summary>
        /// <param name="evaluationId"></param>
        /// <param name="appId"></param>
        /// <param name="classId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private List<DTO.Tb_Corp_EvaluationItem> GetCorpEvaluationScore(int corpEvalId, int evalId, int parentId, string appId, int classId, string areaCode)
        {
            ////取得当前申请已打分的评分项
            var querySub = from sub in dbContext.CorpEvaluationSub
                           where sub.TreeId == corpEvalId && sub.IsDel != true
                           select sub;
            ////取得企业所有评分项
            var query = from item in dbContext.CorpEvaluationItem
                        join itemSub in querySub on item.Id equals itemSub.ItemId into corpItemSubs
                        from itemSubs in corpItemSubs.DefaultIfEmpty()
                        where (item.IsDel != true && item.ClassId == classId && item.ParentID == parentId)
                        select new DTO.Tb_Corp_EvaluationItem
                        {
                            Id = item.Id,
                            Title = item.Title,
                            MaxScore = item.MaxScore,
                            SortIndex = item.SortIndex,
                            ParentID = item.ParentID,
                            Score = itemSubs.Score,
                            TermsIds = itemSubs.TermsIds,
                            Remark = itemSubs.Remark
                        };

            ////加载市级评分项
            if (evalId > 0)
            {
                var queryCitySub = from sub in dbContext.CorpEvaluationSub
                                   where sub.TreeId == evalId && sub.IsDel != true
                                   select sub;
                ////取得企业，市级所有评分项
                query = from item in dbContext.CorpEvaluationItem
                        join itemSub in querySub on item.Id equals itemSub.ItemId into corpItemSubs
                        from itemSubs in corpItemSubs.DefaultIfEmpty()
                        join itemCitySub in queryCitySub on item.Id equals itemCitySub.ItemId into cityItemSubs
                        from itemCitySubs in cityItemSubs.DefaultIfEmpty()
                        where (item.IsDel != true && item.ClassId == classId && item.ParentID == parentId)
                        select new DTO.Tb_Corp_EvaluationItem
                        {
                            Id = item.Id,
                            Title = item.Title,
                            MaxScore = item.MaxScore,
                            SortIndex = item.SortIndex,
                            ParentID = item.ParentID,
                            Score = itemSubs.Score,
                            Score1 = itemCitySubs.Score,
                            TermsIds = itemSubs.TermsIds,
                            Remark = itemSubs.Remark
                        };
            }
            return query.ToList();
        }

        /// <summary>
        /// 创建信用评价主表记录
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="snapGuid"></param>
        /// <param name="isrtUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult CorpEvaluationScoreAdd(Guid corpUserGuid, Guid snapGuid, Guid isrtUserGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            try
            {
                ////取得企业roleid
                int roleId = -1;
                var userInfo = dbContext.T_Sys_Users.Where(o => o.UserGuid == isrtUserGuid).FirstOrDefault();
                roleId = userInfo.RoleID.HasValue ? userInfo.RoleID.Value : -1;
                Tb_Corp_Evaluation_Zbdl corpEval = new Tb_Corp_Evaluation_Zbdl();
                corpEval.KeyGuid = Guid.NewGuid();
                corpEval.CorpUserGuid = corpUserGuid;
                corpEval.SnapGuid = snapGuid;
                corpEval.IsrtUserGuid = isrtUserGuid;
                corpEval.IsrtDate = DateTime.Now;
                corpEval.IsrtUserRole = roleId;
                corpEval.IsDel = false;
                corpEval.TotalScore = 0;
                corpEval.IsVetoed = false;
                corpEval.PostState = 0;
                dbContext.CorpEvaluation.Add(corpEval);
                dbContext.SaveChanges();
                ////添加日志
                SetUserLog("添加信用评价信息", corpEval.KeyGuid.ToString(), corpUserGuid.ToString(), areaCode, "1");
                result.ReturnValue = true;
                result.ReturnValue = corpEval.Id;
                result.Message = "信用评价保存成功！";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "信用评价保存失败" + ex.InnerException;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 返回评价上报状态
        /// </summary>
        /// <param name="corpEvalId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetCorpEvaluationState(int corpEvalId, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            int? postState = dbContext.CorpEvaluation.Where(c => c.Id == corpEvalId && c.IsDel != true).Select(c => c.PostState).FirstOrDefault();
            if (postState == null)
            {
                postState = 0;
            }
            result.ReturnValue = postState;
            return result;
        }

        /// <summary>
        /// 根据角色查看企业评价表的各类打分信息
        /// 2014-5-16 毛凯
        /// </summary>
        /// <param name="snapGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override List<DTO.Tb_Corp_Evaluation> GetCorpEvaluationScoreList(
            string snapGuid,
            string corpUserGuid,
            string roleIds,
            string areaCode)
        {
            Guid _snapGuid = Guid.Empty;
            if (string.IsNullOrEmpty(snapGuid) || !Guid.TryParse(snapGuid, out _snapGuid))
            {
                return null;
            }
            ////获取用户信息
            Guid _corpUserGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out _corpUserGuid))
            {
                return null;
            }
            var query = from e in dbContext.CorpEvaluation
                        join u in dbContext.T_Sys_Users on e.IsrtUserGuid equals u.UserGuid
                        where (e.IsDel == null || e.IsDel == false) && e.SnapGuid == _snapGuid && e.CorpUserGuid == _corpUserGuid
                        select new DTO.Tb_Corp_Evaluation
                        {
                            Id = e.Id,
                            KeyGuid = e.KeyGuid,
                            CorpUserGuid = e.CorpUserGuid,
                            SnapGuid = e.SnapGuid,
                            IsrtDate = e.IsrtDate,
                            IsrtUserGuid = e.IsrtUserGuid,
                            IsrtUserRole = e.IsrtUserRole,
                            IsDel = e.IsDel,
                            TotalScore = e.TotalScore,
                            PostState = e.PostState,
                            IsVetoed = e.IsVetoed,
                            IsrtName = u.Name
                        };
            ////取得当前用户可以查看的记录角色
            List<int> roleIdList = new List<int>();
            if (!string.IsNullOrEmpty(roleIds))
            {
                int roleId = 0;
                string[] roleIdArry = roleIds.Split(',');
                foreach (string arry in roleIdArry)
                {
                    if (int.TryParse(arry, out roleId))
                    {
                        roleIdList.Add(roleId);
                    }
                }
            }
            ////取得查看的记录
            if (roleIdList != null && roleIdList.Count() > 0)
            {
                query = query.Where(o => roleIdList.Contains(o.IsrtUserRole ?? 0));
            }
            query = query.OrderBy(o => o.IsrtDate);
            var result = query.ToList();
            return result;
        }

        /// <summary>
        /// /// <summary>
        /// 打分汇总
        /// 2014-5-16 毛凯
        /// <param name="snapGuid"></param>
        /// <param name="corpUserGuid"></param>
        /// <param name="istUerGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult SaveCorpEvaluation(
            string snapGuid,
            string corpUserGuid,
            string isrtUserGuid,
            string appId,
            int classId,
            string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                Guid _isrtUserGuid = Guid.Empty;
                if (string.IsNullOrEmpty(isrtUserGuid) || !Guid.TryParse(isrtUserGuid, out _isrtUserGuid))
                {
                    result.Result = false;
                    result.Message = "操作用户信息错误！";
                    return result;
                }
                ////申请判断
                result = CheckCorpSnapIsExist(snapGuid, corpUserGuid, 1);
                if (!result.Result)
                {
                    return result;
                }
                Tb_Corp_Snap_Zbdl corpSnap = (Tb_Corp_Snap_Zbdl)result.ReturnValue;
                ////根据snapGuid和corpUserGuid查询本次打分记录
                var evaluationRecord = dbContext.CorpEvaluation.Where(o => o.SnapGuid == corpSnap.KeyGuid && o.IsrtUserGuid == _isrtUserGuid && (o.IsDel == null || o.IsDel == false)).FirstOrDefault();
                if (evaluationRecord == null)
                {
                    result.Result = false;
                    result.Message = "未检测到您本次的评分记录！";
                    return result;
                }
                ////评价状态判断
                result = GetCorpEvaluationState(evaluationRecord.Id, "");
                if (result.Result)
                {
                    if (result.ReturnValue.ToString() != "0")
                    {
                        result.Result = false;
                        result.Message = "信用评价已不能修改！";
                        return result;
                    }
                }
                ////计算总分
                var totalScore = GetScoreSum(evaluationRecord.Id, appId, classId, areaCode);
                evaluationRecord.TotalScore = totalScore;
                dbContext.SaveChanges();
                result.Result = true;
                result.Message = "评分汇总成功！";
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = ex.Message;
            }
            return result;
        }
        #endregion

        #region 代理考核汇总

        /// <summary>
        /// 自评初审汇总表
        /// </summary>
        /// <param name="snapGuid"></param>
        /// <param name="corpRoleIds"></param>
        /// <param name="roleIds"></param>
        /// <param name="appId"></param>
        /// <param name="classId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override List<DTO.Corp_EvaluationScore> CorpEvaluationItemsStatistic(string snapGuid, string corpRoleIds, string cityRoleIds, string appId, int classId, string areaCode)
        {
            Guid keyGuid = Guid.Empty;
            if (!Guid.TryParse(snapGuid, out keyGuid))
            {
                return null;
            }
            ////企业roleId
            int corpRoleId = 0;
            if (!int.TryParse(corpRoleIds, out corpRoleId))
            {
                return null;
            }
            ////市级roleId
            int cityRoleId = 0;
            if (!string.IsNullOrEmpty(cityRoleIds))
            {
                if (!int.TryParse(cityRoleIds, out cityRoleId))
                {
                    return null;
                }
            }
            ////评分申请
            var corpSnap = dbContext.CorpSnap.Where(c => c.KeyGuid == keyGuid && c.IsDel != true).FirstOrDefault();
            if (corpSnap == null)
            {
                return null;
            }
            ////企业自评项
            int? corpEvalId = dbContext.CorpEvaluation.Where(c => c.SnapGuid == keyGuid && c.IsrtUserRole == corpRoleId && c.IsDel != true).OrderByDescending(c => c.Id).Select(c => c.Id).FirstOrDefault();
            if (!corpEvalId.HasValue)
            {
                return null;
            }
            int? evalId = 0;
            ////初审评分项
            if (cityRoleId > 0)
            {
                evalId = dbContext.CorpEvaluation.Where(c => c.SnapGuid == keyGuid && c.IsrtUserRole == cityRoleId && c.IsDel != true).OrderByDescending(c => c.Id).Select(c => c.Id).FirstOrDefault();
            }
            return GetCorpEvaluationItems(corpEvalId.GetValueOrDefault(), evalId ?? 0, appId, classId, areaCode);
        }

        /// <summary>
        /// 取得汇总评分项
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="classId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public List<DTO.Corp_EvaluationScore> GetCorpEvaluationItems(int corpEvalId, int evalId, string appId, int classId, string areaCode)
        {
            var list = dbContext.CorpEvaluationItem.Where(c => c.IsDel != true && c.ClassId == classId && c.ParentID == 0).ToList();
            List<DTO.Corp_EvaluationScore> list_D = new List<DTO.Corp_EvaluationScore>();
            ////实体转换
            foreach (Tb_Corp_EvaluationItem_Zbdl item in list)
            {
                DTO.Corp_EvaluationScore work_D = new DTO.Corp_EvaluationScore();
                work_D.Id = item.Id;
                work_D.MaxScore = item.MaxScore;
                work_D.ParentID = item.ParentID;
                work_D.SortIndex = item.SortIndex;
                work_D.Title = item.Title;
                work_D.Type = item.Type;
                var items = GetCorpEvaluationScore(corpEvalId, evalId, item.Id, appId, classId, areaCode);
                work_D.CorpEvaluationItems = items;
                work_D.ChildCount = items.Count();
                ////计算企业自评分
                decimal score = items.Select(i => i.Score).Sum().HasValue ? (decimal)items.Select(i => i.Score).Sum() : 0;
                work_D.Score = GetScore(item.MaxScore, score, item.Type);
                ////计算初审自评分
                if (evalId > 0)
                {
                    decimal score1 = items.Select(i => i.Score1).Sum().HasValue ? (decimal)items.Select(i => i.Score1).Sum() : 0;
                    work_D.Score1 = GetScore(item.MaxScore, score1, item.Type);
                }
                list_D.Add(work_D);
            }
            return list_D;
        }

        /// <summary>
        /// 主管信用评价实际初审意见汇总表
        /// </summary>
        /// <param name="evaluationId"></param>
        /// <param name="appId"></param>
        /// <param name="classId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override List<DTO.CorpSnapEvaluationScore> GetCorpSnapEvaluationScoreSum(string startDate, string endDate, string corpRoleIds, string cityRoleIds, string appId, string areaCode)
        {
            var list_E=new RN.ERP.ZbdlryDAL.KaoHeDAL().GetCorpSnapEvaluationScoreSum(startDate, endDate, appId, corpRoleIds, cityRoleIds, areaCode);
            List<DTO.CorpSnapEvaluationScore> list_D = new List<DTO.CorpSnapEvaluationScore>();
            ////实体转换
            foreach (CorpSnapEvaluationScore_zbdl item in list_E)
            {
                DTO.CorpSnapEvaluationScore item_D = new DTO.CorpSnapEvaluationScore();
                EntityHelper.ConvertEntity2OtherEntity(item, item_D);
                list_D.Add(item_D);
            }
            return list_D;
        }

        /// <summary>
        /// 返回拥有查询证书的人员数
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override int GetCorpPersonCert(string corpUserGuid, string areaCode, int typeFlags)
        {
            ////判断企业是否存在
            var result = CheckCompanyIsExist(corpUserGuid);
            if (!result.Result)
            {
                return 0;
            }
            ////取得企业信息
            Tb_Corp_CompanyInfo_Zbdl companyInfo = (Tb_Corp_CompanyInfo_Zbdl)result.ReturnValue;
            var query = from item in dbContext.ManagerInfoFlow
                        join itemSub in dbContext.Emp_Qualities on item.EmpGuid equals itemSub.EmpGuid
                        where item.IsDel != true && itemSub.IsDel != true 
                        && item.CorpGuid == companyInfo.CorpUserGuid && item.FlowAreaCode.StartsWith(areaCode)
                        select new
                        {
                            EmpGuid = itemSub.EmpGuid,
                            typeFlags=itemSub.TypeFlags
                           
                        };
            if (typeFlags > 0)
            {
                query = query.Where(q => q.typeFlags == typeFlags);
            }
            return query.Distinct().Count();
        }
        #endregion

        #region 企业评价信息子表
        public override DTO.OperationResult AddCorpEvaluationSub(string corpEvaSubstr)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Tb_Corp_EvaluationSub_Zbdl corpEvaSub = JsonConvert.DeserializeObject<Tb_Corp_EvaluationSub_Zbdl>(corpEvaSubstr);
            ////取得评价信息
            var corpEvaluation = dbContext.CorpEvaluation.Where(c => c.Id == corpEvaSub.TreeId && c.IsDel != true).FirstOrDefault();
            if (corpEvaluation == null)
            {
                result.Result = false;
                result.Message = "没有查询到评价信息！";
                return result;
            }
            if (corpEvaluation.PostState > 0)
            {
                result.Result = false;
                result.Message = "信用评价已上报审核，不能再评分！";
                return result;
            }
            ////更新评分
            var sub = dbContext.CorpEvaluationSub.Where(s => s.TreeId == corpEvaSub.TreeId && s.ItemId == corpEvaSub.ItemId).FirstOrDefault();
            if (sub == null)
            {
                dbContext.CorpEvaluationSub.Add(corpEvaSub);
            }
            else
            {
                sub.Score = corpEvaSub.Score;
                sub.TermsIds = corpEvaSub.TermsIds;
                sub.Remark = corpEvaSub.Remark;
                dbContext.Entry(sub).State = EntityState.Modified;
            }
            if (dbContext.SaveChanges() > 0)
            {
                result.Result = true;
                result.Message = "添加成功";
            }
            else
            {
                result.Result = false;
                result.Message = "添加失败";
            }
            return result;
        }

        public override string GetCorp_EvaluationSub(int itemID, int treeID)
        {
            return JsonConvert.SerializeObject(dbContext.CorpEvaluationSub.Where(s => s.TreeId == treeID && s.ItemId == itemID).FirstOrDefault());
        }

        #endregion
    }
}
